<?php
define('TEMP_FILE', './Uploads/image');
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2015/10/29
 * Time: 15:19
 */
class TestAction extends Action
{
    public function updateSeckillProduct(){
        $productModel = M("module_product");
        $sql = "select id,json from wx_module_product where playType = 4 and deleted = 0 and `isRemoved` =0";
        $list = $productModel->query($sql);
        foreach($list as $key=>$value){
            $json = json_decode($value['json'],true);
            if($json['seckillEndtime']){
                $json['seckillEndTime'] = $json['seckillEndtime'];
                unset($json['seckillEndtime']);
                $data = null;
                $data['json'] = json_encode($json);
                $productModel->where("id=".$value['id'])->save($data);
            }

        }
    }

    public function InsertIMI()
    {
        Session::switchCustomer(0);
        $Model_Customer     = M('customer');
        $Model_IndMediaInfo = M('ind_media_info');

        $Res_Customer = $Model_Customer->select();

        foreach ($Res_Customer as $k_c => $v_c) {

            $data_IMI = [
                'id' => $v_c['id'],
                'cid' => $v_c['id'],
                'uuid' => $v_c['uuid'],
                'token' => $v_c['token'],
                'expired' => $v_c['expired'],
                'appid' => $v_c['appid'],
                'appsecret' => $v_c['appsecret'],
                'accessToken' => $v_c['accessToken'],
                'accessExpiration' => $v_c['iaccessExpirationd'],
                'isApiAuth' => $v_c['isApiAuth'],
                'isAutoGroup' => $v_c['isAutoGroup'],
                'wxAppAppid' => $v_c['wxAppAppid'],
                'wxAppSecret' => $v_c['wxAppSecret'],
                'wxAppAccessToken' => $v_c['wxAppAccessToken'],
                'wxAppAccessExpiration' => $v_c['wxAppAccessExpiration'],
                'mode' => $v_c['mode'],
                'refreshToken' => $v_c['refreshToken'],
                'third_platform_appid' => $v_c['third_platform_appid'],
                'type' => 1,
                'status' => 1,
                'needTailPic' => 0,
                'TailPicUrl' => '',
                'isDefault' => 1,
                'createTime' => date('Y-m-d H:i:s'),
                'deleted' => 0,
                'reviewer' => 'NULL',
                'ifReview' => 0
            ];
            $Res_IndMediaInfo = $Model_IndMediaInfo->add($data_IMI);

            if (!$Res_IndMediaInfo) {
                echo $v_c['id'] . '----' . $Model_IndMediaInfo->getLastSql() . '<br />';
            }
        }

    }

    public function updateQuanUid($start=0,$limit=100){
        set_time_limit(0);
        Session::switchCustomer(0);
        M()->query('set names utf8');

        $sql = "select uId,cId,qId,openid " .
            "from miyouquan_170914.wx_mimall_user " .
            "where cId is not null " .
            "limit " . $start . "," . $limit;
        $list = M()->query($sql);
        echo count($list);
        foreach($list as $key=>$value){
            $userId = M()->query("select id from miyouquan.wx_".$value['cId']."_user where userName = '".$value['openid']."'");
            if(!$userId||!$value['uId']){
                continue;
            }
            $quanUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_quan_user where qid = ".$value['qId']." and uid = ".$value["uId"]);
            $quanRereeUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_quan_user where qid = ".$value['qId']." and refereeUid = ".$value["uId"]);
            $friendUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_miaccount_friend where quanId = ".$value['qId']." and uId = ".$value["uId"]);
            $lordUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_miaccount_lord where quanId = ".$value['qId']." and uId = ".$value["uId"]);
            $teamLeader = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_quan_team where quanId = ".$value['qId']." and teamLeader = ".$value["uId"]);
            $monthUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_quan_user_month_statistics where quanId = ".$value['qId']." and uId = ".$value["uId"]);
            $vendorUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_quanuser_vendor where qId = ".$value['qId']." and miUId = ".$value["uId"]);
            $orderMiuid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_product_order where qId = ".$value['qId']." and miUid = ".$value["uId"]);
            $orderUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_product_order where qId = ".$value['qId']." and uId = ".$value["uId"]);
            $orderRefereeUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_product_order where qId = ".$value['qId']." and refereeUid = ".$value["uId"]);
            $orderParentRefereeUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_product_order where qId = ".$value['qId']." and parentRefereeUid = ".$value["uId"]);
            $orderDetailMiuid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_module_product_order_detail where qId = ".$value['qId']." and miUid = ".$value["uId"]);
            $mimallUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_mimall_user where qId = ".$value['qId']." and uId = ".$value["uId"]);
            $mimallMiuid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_mimall_user where qId = ".$value['qId']." and miUid = ".$value["uId"]);
            $tixianUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_miconis_tixian where quanId = ".$value['qId']." and uId = ".$value["uId"]);
            $contentUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_micontent where qid = ".$value['qId']." and uId = ".$value["uId"]);
            $regpeopleUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_miactivity_vote_regpeople where quanId = ".$value['qId']." and uId = ".$value["uId"]);
            $praiseUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_mishare_praise where qid = ".$value['qId']." and uid = ".$value["uId"]);
            $commentUid = M()->query("select GROUP_CONCAT(id) as ids from miyouquan_170914.wx_mishare_comment where qId = ".$value['qId']." and uId = ".$value["uId"]);
            M()->query("INSERT INTO miyouquan_170914.wx_update_uid(uid,quanUid,quanRereeUid,friendUid,lordUid,teamLeader,monthUid,vendorUid,orderMiuid,orderUid,orderRefereeUid,orderParentRefereeUid,"
                        ."orderDetailMiuid,mimallUid,mimallMiuid,tixianUid,contentUid,regpeopleUid,praiseUid,commentUid) values('".$userId[0]['id']."','".$quanUid[0]['ids']."','".$quanRereeUid[0]['ids'].
                        "','".$friendUid[0]['ids']."','".$lordUid[0]['ids']."','".$teamLeader[0]['ids']."','".$monthUid[0]['ids']."','".$vendorUid[0]['ids']."','".$orderMiuid[0]['ids']."','".$orderUid[0]['ids'].
                        "','".$orderRefereeUid[0]['ids']."','".$orderParentRefereeUid[0]['ids']."','".$orderDetailMiuid[0]['ids']."','".$mimallUid[0]['ids']."','".$mimallMiuid[0]['ids']."','".$tixianUid[0]['ids']."','".
                        $contentUid[0]['ids']."','".$regpeopleUid[0]['ids']."','".$praiseUid[0]['ids']."','".$commentUid[0]['ids']."')");
        }

    }
    //更新商城信息
    public function updateMallInfo(){
        Session::switchCustomer(0);
        $mimall = M("mimall");
        $list = $mimall->where("deleted=0")->select();
        echo $mimall->getLastSql()."<br/>";
        foreach($list as $key=>$value){
            $id = $mimall->table("wx_".$value['fromCustomerId']."_module_mall_store")->getField("id");
            $data = null;
            $data['qrcodeBack'] = $value['qrcodeBack'];
            $data['qrcodeLocation'] = $value['qrcodeLocation'];
            $data['qrcodeSize'] = $value['qrcodeSize'];
            $data['mallHue'] = $value['mallHue'];
            $mimall->table("wx_".$value['fromCustomerId']."_module_mall_store")->where("id=$id")->save($data);
            echo $mimall->getLastSql()."<br/>";
        }

    }
    //更新用户注册信息
   public function updateUser($start=0,$limit=10000){
       set_time_limit(0);
       Session::switchCustomer(0);
        $mimall = M("mimall_user");
       $table= M("");
       $list = $mimall->alias("a")
           ->join("inner join wx_all_user b on a.uId=b.id")
           ->field("a.id,a.uId,a.miUid,a.cId,b.weixinUserId,b.fullName,b.phone")
           ->where("b.weixinUserId is not null and a.cId is not null")
           ->limit($start,$limit)
           ->select();
           echo count($list);
       foreach($list as $key=>$value){
           $userid = $table->table("wx_".$value['cId']."_user_weixin_info")->where("id=".$value['weixinUserId'])->getField("userId");
           $data = null;
           $data['fullName']= $value['fullName'];
           $data['phone']= $value['phone'];
           $table->table("wx_".$value['cId']."_user")->where("id=$userid")->save($data);
       }
   }
    
    public function updateQuanUser($start=0,$limit=100){
        set_time_limit(0);
        Session::switchCustomer(0);
        M()->query('set names utf8');
        $sql = "select * " .
            "from miyouquan_170914.wx_update_uid " .
            "limit " . $start . "," . $limit;
        $list = M()->query($sql);
        echo count($list);
        foreach($list as $key=>$value){
            $value['quanUid']?M()->query("update miyouquan.wx_quan_user set uid = ".$value['uid']." where id in (".$value['quanUid'].")"):'';
            $value['quanRereeUid']?M()->query("update miyouquan.wx_quan_user set refereeUid = ".$value['uid']." where id in (".$value['quanRereeUid'].")"):'';
            $value['friendUid']?M()->query("update miyouquan.wx_miaccount_friend set uId = ".$value['uid']." where id in (".$value['friendUid'].")"):'';
            $value['lordUid']?M()->query("update miyouquan.wx_miaccount_lord set uId = ".$value['uid']." where id in (".$value['lordUid'].")"):'';
            $value['teamLeader']?M()->query("update miyouquan.wx_quan_team set teamLeader = ".$value['uid']." where id in (".$value['teamLeader'].")"):'';
            $value['monthUid']?M()->query("update miyouquan.wx_quan_user_month_statistics set uId = ".$value['uid']." where id in (".$value['monthUid'].")"):'';
            $value['vendorUid']?M()->query("update miyouquan.wx_module_quanuser_vendor set miUId = ".$value['uid']." where id in (".$value['vendorUid'].")"):'';
            $value['orderMiuid']?M()->query("update miyouquan.wx_module_product_order set miUid = ".$value['uid']." where id in (".$value['orderMiuid'].")"):'';
            $value['orderUid']?M()->query("update miyouquan.wx_module_product_order set uId = ".$value['uid']." where id in (".$value['orderUid'].")"):'';
            $value['orderRefereeUid']?M()->query("update miyouquan.wx_module_product_order set refereeUid = ".$value['uid']." where id in (".$value['orderRefereeUid'].")"):'';
            $value['orderParentRefereeUid']?M()->query("update miyouquan.wx_module_product_order set parentRefereeUid = ".$value['uid']." where id in (".$value['orderParentRefereeUid'].")"):'';
            $value['orderDetailMiuid']?M()->query("update miyouquan.wx_module_product_order_detail set miUid = ".$value['uid']." where id in (".$value['orderDetailMiuid'].")"):'';
            $value['mimallUid']?M()->query("update miyouquan.wx_mimall_user set uId = ".$value['uid']." where id in (".$value['mimallUid'].")"):'';
            $value['mimallMiuid']?M()->query("update miyouquan.wx_mimall_user set miUid = ".$value['uid']." where id in (".$value['mimallMiuid'].")"):'';
            $value['tixianUid']?M()->query("update miyouquan.wx_miconis_tixian set uId = ".$value['uid']." where id in (".$value['tixianUid'].")"):'';

            $value['contentUid']?M()->query("update miyouquan.wx_micontent set uId = ".$value['uid']." where id in (".$value['contentUid'].")"):'';
            $value['regpeopleUid']?M()->query("update miyouquan.wx_miactivity_vote_regpeople set uId = ".$value['uid']." where id in (".$value['regpeopleUid'].")"):'';
            $value['praiseUid']?M()->query("update miyouquan.wx_mishare_praise set uid = ".$value['uid']." where id in (".$value['praiseUid'].")"):'';
            $value['commentUid']?M()->query("update miyouquan.wx_mishare_comment set uId = ".$value['uid']." where id in (".$value['commentUid'].")"):'';
        }
    }
    public function updateMiyouInfo($start=0,$limit=1000){
        M()->query('set names utf8');

        $sql = "select a.openid, " .
                   "a.`cId`, " .
                   "b.`fullName`, " .
                   "b.`phone`, " .
                   "b.`wxNumber`, " .
                    "b.`isBind` " .
              "from miyouquan_170914.wx_mimall_user a " .
              "inner join wx_all_user b on a.uId= b.id " .
             "where a.uid is not null " .
               "and fullName<> '' " .
               "limit " . $start . "," . $limit;
        $result = M()->query($sql);
        echo count($result) . '======' . 'sql = ' . M()->getLastSql() . '<br /><br /><br />';

        foreach ($result as $k => $v) {

            $createSql = "ALTER TABLE wx_" . $v['cId'] . "_user" .
                " ADD COLUMN isBind tinyint(4) NULL DEFAULT 0";
            $createRes = M()->query($createSql);

            echo  'createRes = ' . $createRes . '===== ';

            $upSql = "update wx_" . $v['cId'] . "_user 
                       set fullName='" . $v['fullName'] . "',
                           phone=" . $v['phone'] . ",
                           wxNumber='" . $v['wxNumber'] . "',
                           isBind=" . $v['isBind'] . "
                     where userName='" . $v['openid'] . "'";

            $result = M()->query($upSql);
            echo 'result = ' . $result . '======' . 'sql = ' . M()->getLastSql() . '<br />';
        }

    }

    /**
     * 获取微信历史素材
     * @param $mediaId /自媒体id
     * @return string
     * @throws Exception
     */
    public function getWxNews($mediaId)
    {
        Session::init();
        $accessToken = WeixinApi::getAccessToken(true,null,null,$mediaId);
        if(!$accessToken){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'获取accessToken失败'
            ]);
            return;
        }
        //测试获取公众号素材总数
        $total = self::getWxNewsNum($accessToken);
        $count = 10; //每次拉取十条
        $num  = $total<=0 ? 0 : ceil($total/$count);
        for($i=0;$i<$num;$i++){
            $dataList = [];
            //分页获取图文素材
            $url= "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=$accessToken";
            $param = json_encode([
                "type"=>'news',
                "offset"=>$i*$count,        //每次请求偏移量
                "count"=>$count             //每次请求数量
            ]);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = json_decode(curl_exec($ch),true);
            curl_close($ch);
            $material_table = M('material');
            //处理获取的数组
            if($result['item']){
                foreach($result['item'] as $val){
                    $dataArr = [];
                    $title = '';
                    $xml = '';

                    //如果单图文,直接判断表中是否存在
                    if(count($val['content']['news_item']) == 1){
                        $serRet = $material_table->where(['module'=>'material','name'=>$val['content']['news_item'][0]['title'],'media_id'=>$mediaId, 'type'=>'news'])->find();
                        if($serRet){
                            continue;
                        }
                    }

                    if($val['content']['news_item']){
                        $newResult = self::assembleXml($val['content']['news_item']);
                        $title = trim($newResult['title'],',');
                        $serRet = $material_table->where(['module'=>'material','name'=>$title,'media_id'=>$mediaId, 'type'=>'news'])->find();
                        if($serRet){
                            //表中存在,直接跳过
                            continue;
                        }
                        $xml = $newResult['xml'];
                    }
                    $dataArr['name'] = $title;  //标题拼接
                    //$dataArr['media_id'] = $val['media_id'];  //media_id暂不存,避免永久素材限制
                    $dataArr['module'] = 'material';
                    $dataArr['xml'] = $xml;
                    $dataArr['updateTime'] = date('Y-m-d H:i:s', $val['update_time']);
                    $dataArr['type'] = 'news';
                    $dataArr['public'] = 0;
                    $dataArr['backups'] = 0;
                    $dataArr['media_id'] = $mediaId;
                    $ret = $material_table->add($dataArr);
                    if(!$ret){
                        echo 'jie--------111';
                        var_dump($material_table->getDbError());
                        var_dump($material_table->getLastSql());
                    }

                    //$dataList[] = $dataArr;
                }

                /*if($dataList){
                    $wxSaveSql = 'insert into wx_3_material (`name`,`module`,`xml`,`updateTime`,`type`,`public`) VALUES ';
                    foreach ($dataList as $v) {
                        $wxSaveSql .= "('" . $v['name'] . "','" . $v['module'] . "','" . $v['content'] . "','" . $v['update_time'] . "','news', 0),";
                    }
                    $wxSaveSql = trim($wxSaveSql, ',') . ';';
                    $ret = M()->execute($wxSaveSql);
                    if(!$ret){
                        echo 'jie--------111';
                        var_dump(M()->getLastSql());
                    }
                }*/
            }
        }
        Output::instance()->resultCode();
    }
    /**
     * 组装xml
     * @param array $item /一条图文的内容
     * @return string
     */
    public function assembleXml($item)
    {
        $downLoadDir = TEMP_FILE;//临时目录
        $title = '';
        $xml = '<xml><Articles>';
        foreach ($item as $val) {
            $title .= $val['title'].',';
            //将内容中的图片URL处理成oss上面的图片
            $content = $val['content'];
            if($val['content']){
                $content = self::replaceImg($val['content'], $downLoadDir);
            }
            $thumb_url = $val['thumb_url'];
            if($val['thumb_url']){
                $thumb_url = self::replaceImg($val['thumb_url'], $downLoadDir, 1);
            }
            $xml .= '<item>
<title><![CDATA[' . $val['title'] . ']]></title>
<content><![CDATA[<p>' .$content . '<img class="loadingclass" id="loading_j6ublzmf" src="./thirdsources/editor_135.assets/themes/default/images/spacer.gif"/></p>]]></content>
<picUrl><![CDATA[' . $thumb_url . ']]></picUrl>
<author><![CDATA[' . $val['author'] . ']]></author>
<description><![CDATA[' . $val['digest'] . ']]></description>
<content_source_url><![CDATA[' . $val['url'] . ']]></content_source_url>
</item>';
        }
        $xml .= '</Articles></xml>';
        return [
            'title' => $title,
            'xml' => $xml
        ];
    }
    /**
     * 将图片上传到oss,替换文章中的图片路径
     * @param array $item /一条内容
     * @param string $downLoadDir 临时保存文件夹
     * @param int $type /判断是内容还是封面图片
     * @return string
     */
    public function replaceImg($item, $downLoadDir, $type=0){
        $cid = session('customerId')?session('customerId'):3;
        //保存路径
        if(!is_dir($downLoadDir)){
            self::createDir($downLoadDir);
        }

        if($type == 1){
            //处理封面图片
            $img=file_get_contents($item);
            if($img == false){
                return $item;
            }

            $fileimgname = time()."-".rand(1000,9999).'.jpeg';
            $filecachs=$downLoadDir."/".$fileimgname;
            //先保存在本地
            $int = file_put_contents($filecachs, $img);
            if(!$int){
                return $item;
            }
            //上传oss,获取链接
            $upRet = R('Upload/uploadLocalFileToOss', [$fileimgname, $filecachs]);
            $fileInfo = $upRet->path;
            if(!$fileInfo){
                return $item;
            }
            return $fileInfo;
        }

        //处理图文中的图片,匹配图片的src
        $item = str_replace('data-src', 'src', $item);
        preg_match_all('#<img.*?src="([^"]*)".*?>#i', $item, $match);
        foreach($match[1] as $imgUrl){
            $img=file_get_contents($imgUrl);
            if($img == false){
                continue;
            }
            if(!empty($img)) {
                //保存图片到服务器
                $fileimgname = time()."-".rand(1000,9999).'.jpeg';
                $filecachs=$downLoadDir."/".$fileimgname;
                //先保存在本地
                $int = file_put_contents( $filecachs, $img);
                if(!$int){
                    continue;
                }
                //上传oss,获取链接
                $upRet = R('Upload/uploadLocalFileToOss', [$fileimgname, $filecachs]);
                $fileInfo = $upRet->path;
                if(!$fileInfo){
                    continue;
                }
                //替换文章中的路径
                $item=str_replace($imgUrl,$fileInfo,$item);
            }
        }
        return $item;
    }

    /**
     * 获取图文素材的数量
     * @param $accessToken
     * @return int
     */
    public function getWxNewsNum($accessToken){
        $countUrl= "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=$accessToken";
        $ch = curl_init($countUrl) ;
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        $res= json_decode(curl_exec($ch), true);
        curl_close($ch);
        return $res['news_count'];
    }

    /**
     * @param $params /执行任务所填参数
     */
    public function addTest()
    {
        $redis = new Redis();
        var_dump($redis);
        $redis = new RedisAPI();
        var_dump($redis);exit;

    }

    /**
     * @param $params /执行任务所填参数
     */

    public function getTest()
    {
        $redis = new RedisAPI();
        for($i=0;$i<8;$i++){
            $redis->lPush('test', $i);
        }
        $bool = true;
        while($bool){
            $result = $redis->rPop('list');
            echo $result;
            if(!$result){
                $bool = false;
            }
        }

        echo '输出成功';exit;
    }

    public function __get($property_name)
    {

        throw new Exception('方法不存在');
    }

    /**
     * 下载活动数据,一个渠道一个文件夹,每个文件夹包含Excel和所有的图
     * @param $taskInfo /整条任务信息
     */
    public function getPartakeList($taskInfo)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $cid = Session::$user["customerId"];
        Session::switchCustomer(0);
        $miactivity_visit_db = M("miactivity_visit");
        $miactivity_channel_db = M('miactivity_channel');
        $miactivity_photo_share_db = M("miactivity_photo_share");
        $taskQueue_table = M('task_queue');
        Session::switchCustomer($cid);

        $param = json_decode($taskInfo['param'],true);
        $activity_id = $param['activity_id'];

        $map = array();
        $map['c.activityId'] = $activity_id;
        $map["c.cid"] = $cid;

        //查询所有的参与记录
        $list = $miactivity_photo_share_db->alias('c')
            ->field('c.*, c.name as user_name')
            ->where($map)
            ->distinct(true)
            ->getField('id,name,nickname,phone,picUrls,createTime,channelId');
        $channel_map = array();
        $channel_map['cid'] = $cid;
        $channel_map['deleted'] = 0;
        $channel_list = $miactivity_channel_db->where($channel_map)->getField('id,name');

        //将参加数据按照渠道id区分组装成二维数组;
        $visit_map = $excelArr = $imgArr = array();
        foreach ($list as $key => $value) {
            $channelId = $value['channelId'] ? $value['channelId'] : 0;
            //保存图片数据
            $oneArr = [];
            $oneArr['img'] = explode(',', $value['picUrls']);
            $oneArr['id'] = $value['id'];
            $imgArr[$channelId][] = $oneArr;

            //保存参与数据到Excel
            $value['channel_name'] = $channel_list[$channelId];
            $visit_map['partakeId'] = $value['partakeId'];
            $visit_map['activityId'] = $activity_id;
            $visit_map['cid'] = $cid;
            $visit_count = $miactivity_visit_db->where($visit_map)->group('userId')->count();
            $value['visit_count'] = $visit_count ? $visit_count : 0;
            unset($value['channelId']);
            unset($value['picUrls']);
            $excelArr[$channelId][] = $value;
        }

        //生成保存文件的文件夹
        $DirCommon = './Uploads/user-'.$cid.'channelData';
        if(!is_dir($DirCommon)){
            self::createDir($DirCommon);
        }

        //循环获取Excel
        foreach ($excelArr as $k => $val) {
            $excelDirName = $DirCommon . '/' . $k;
            try {
                //创建目录
                if(!is_dir($excelDirName)){
                    self::createDir($excelDirName);
                }
                //保存Excel
                self::exportGetData($k, $val, $excelDirName);
            } catch (Exception $e) {
                Log::write('任务执行失败-----------info:' . $e->getMessage());
                continue;
            }
        }

        //下载图片
        foreach ($imgArr as $key => $value) {
            $imgDirName = $DirCommon . '/' . $key;
            foreach ($value as $k => $val) {
                if (count($value) > 0) {
                    foreach ($val['img'] as $imgKey => $imgVal) {
                        //文件名组成以单条数据编号加图片编号
                        $imgFileName = $imgDirName . '/' . $val['id'] . '-' . $imgKey;
                        try {
                            self::getImage($imgVal, $imgFileName);
                        } catch (Exception $e) {
                            Log::write('任务执行失败-----------info:' . $e->getMessage() . 'URL:' . $imgVal);
                            continue;
                        }
                    }
                }
            }
        }

        //压缩下载好的文件
        $zip = new ZipArchive();
        //保存的zip文件名字以及路径
        $downFileName = './Uploads/user-'.$cid.'channelDataZip.zip';
        if ($zip->open($downFileName, ZipArchive::OVERWRITE) === TRUE) {
            //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方
            try {
                self::addFileToZip($DirCommon, $zip);
                //关闭处理的zip文件
                $zip->close();
                //将成功结果保存到任务表中
                $result = $taskQueue_table->where(array('id'=>$taskInfo['id']))->save(array(
                    'result'=>json_encode(array(
                        'code'=>1, //1代表成功
                        'downUrl'=>$downFileName
                    ))
                ));
            } catch (Exception $e) {
                //压缩失败
                $result = $taskQueue_table->where(array('id'=>$taskInfo['id']))->save(array(
                    'result'=>json_encode(array(
                        'code'=>0, //0代表任务失败
                        'downUrl'=>''
                    ))
                ));
                echo $e->getMessage();
            }
        }
        //将文件删除,只保留zip
        self::delDir($DirCommon);
        if(!is_numeric($result)){
            Log::write('任务执行失败------------SQL:'.$taskQueue_table->getLastSql());
            throw new Exception('保存任务结果失败');
        }
        return true;
    }

    /**
     * 下载压缩好的zip文件
     * @param $taskId /任务id
     */
    public function getSharePhotoZip($taskId)
    {
        $relVal = Session::init();
        if (!$relVal) {
            Output::instance()->object(code_access_denied);
        }

        $cid = Session::init();
        Session::switchCustomer(0);
        $taskQueue_table = M('task_queue');
        Session::switchCustomer($cid);
        //获取下载URL
        $resultInfo = $taskQueue_table->where(array('id' => $taskId))->getField('result');
        $fileName = json_decode($resultInfo, true)['downUrl'];
        /* echo '<pre>';
         var_dump($fileName);
         echo '<pre>';exit;*/
        if (file_exists($fileName)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($fileName));
            readfile($fileName);
            exit;
        }
    }

    /**
     * 删除文件夹
     * @param $dir /需要删除的文件路径
     */

    public function delDir($dir){
        if (rmdir($dir)==false && is_dir($dir)) {
            if ($handle = opendir($dir)) {
                while (false !== ($filename = readdir($handle))) {
                    if ($filename == '..' || $filename == '.')   // 排除两个特殊目录
                        continue;
                    $path = $dir . '/' . $filename;
                    // 如果是目录，递归删除
                    if (is_dir($path)) {
                        self::delDir($path);
                    } else {
                        // 如果是文件，直接删除
                        unlink($path);
                    }
                }
            };
            // 关闭
            closedir($handle);
            //删除文件后删除空目录
            rmdir($dir);
        }else{
            throw new Exception('删除失败');
        }
    }

    /**
     * 压缩文件夹
     * @param $path /需要压缩的文件夹路径
     * @param $zip /PHP压缩类的对象
     */
    public function addFileToZip($path, $zip)
    {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        while (($filename = readdir($handler)) !== false) {
            //文件夹文件名字为'.'和‘..’，不要对他们进行操作
            if ($filename != "." && $filename != "..") {
                // 如果读取的某个对象是文件夹，则递归
                if (is_dir($path . "/" . $filename)) {
                    self::addFileToZip($path . "/" . $filename, $zip);
                } else { //将文件加入zip对象
                    $zip->addFile($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }

    /**
     * 创建对应的文件夹
     * @param $save_dir /文件夹名称
     * @throws Exception
     */
    public function createDir($save_dir)
    {
        //$save_dir = APP_PATH.'../updateDoc/datas';
        if (trim($save_dir) == '') {
            //保存的文件夹
            $save_dir = './';
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            //创建文件夹失败
            throw new Exception('创建文件夹失败');
        }
    }

    /**
     * 导出晒照片活动数据
     * @param $channelId /渠道id
     * @param $excelData /渠道数据
     * @param $excelDirName /保存单个渠道的文件夹
     */
    public function exportGetData($channelId, $excelData, $excelDirName)
    {

        $fileName = $excelDirName . '/' . $excelData['channel_name'] . $channelId; //设置文件名
        $expCellName = array(
            array('id', '编号'),
            array('channel_name', '渠道'),
            array('nickname', '昵称'),
            array('name', '姓名'),
            array('phone', '手机号码'),
            array('createTime', '创建时间')
        );
        $expTableDataTemp = array();
        /*echo '<pre>';
        var_dump($excelData);
        echo '</pre>';exit;*/
        foreach ($excelData as $key => $value) {
            $expTableDataTemp[] = $value;
        }
        if ($expTableDataTemp) {
            self::objArrayExcel($fileName, $expCellName, $expTableDataTemp);
        }
    }


    /**
     * 输出Excel
     * @param $expCellName 表格数据描述，即表头
     * @param $expTableData 表格数据
     * @param $fileName 保存文件名
     */
    public function objArrayExcel($fileName, $expCellName, $expTableData)
    {
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new PHPExcel();

        /** 导出数据量比较大, 这里设置超时时间无限制, 无论之前脚本运行多长时间, 此函数都会重启超时计时器, 从0重新计时 */
        set_time_limit(0);
        // 设置Excel文件缓存
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
        $cacheSettings = array('memoryCacheSize' => '8MB');
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        if ($expCellName && $expCellName !== '') {
            for ($i = 0; $i < $cellNum; $i++) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i][1]);
            }
            // Miscellaneous glyphs, UTF-8
            for ($i = 0; $i < $dataNum; $i++) {

                for ($j = 0; $j < $cellNum; $j++) {
                    $XS_SJ = $expTableData[$i][$expCellName[$j][0]];
                    //用' ' 处理数字为文本,以免excel中数字太大时科学计数法导致错误
                    $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 2), ' ' . $XS_SJ);//控制不能显示科学计数数字。
                }
            }
        } else {
            echo 111;
            exit;
            $i = 0;

            foreach ($expTableData as $key => $row) {
                $j = 0;
                if ($row["isNum"]) {
                    $isNum = explode(",", $row["isNum"]);
                    unset($row["isNum"]);
                }
                $title = $row['istitle'];
                if ($title && $title == 1) {
                    $expTableData[$key] = array_pop($row);
                }
                foreach ($row as $k1 => $cell) {
                    if ($title && $title == 1) {
                        $objPHPExcel->getActiveSheet(0)->getStyle($cellName[$j] . ($i + 1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
                        $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getFill()->getStartColor()->setARGB('00F0F0F0');
                        $objPHPExcel->getActiveSheet()->getRowDimension($i + 1)->setRowHeight(24);
                    }
                    if ($isNum && in_array($j, $isNum) && $i != 0) {
                        $objPHPExcel->getActiveSheet()->setCellValueExplicit($cellName[$j] . ($i + 1), ' ' . $cell, PHPExcel_Cell_DataType::TYPE_NUMERIC);
                    } else {
                        $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 1), ' ' . $cell);
                    }
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j])->getAlignment()->setWrapText(true);
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getStyle($cellName[$j] . ($i + 1))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                    $objPHPExcel->getActiveSheet()->getColumnDimension($cellName[$j])->setWidth(18);
                    $objPHPExcel->getActiveSheet()->getRowDimension($i + 2)->setRowHeight(40);
                    $j++;
                }
                $i++;
            }
        }
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save($fileName . '.xls');
        //exit;
    }

    /**
     * 下载远程图片保存到指定文件夹
     * @param $url /图片远程url
     * @param string $filename /保存的文件路径
     * @return array 返回值
     * @throws Exception
     */
    public function getImage($url, $filename = '')
    {
        if (trim($url) == '') {
            throw new Exception('图片路径不能为空');
        }

        if (trim($filename) !== '') {//保存文件名
            $ext = strrchr($url, '.');
            if ($ext != '.png' && $ext != '.jpg') {
                throw new Exception('图片后缀不符合要求');
            }
            $filename .= $ext;
        }
        /*echo '<pre>';
        var_dump($filename);
        echo '</pre>';exit;*/
        //获取远程文件所采用的方法
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $img = curl_exec($ch);
        curl_close($ch);
        if (!$img) {
            throw new Exception('获取图片失败');
        }
        $fp2 = @fopen($filename, 'a');
        if (!$fp2) {
            throw new Exception('打开图片失败');
        }
        fwrite($fp2, $img);
        fclose($fp2);
        unset($img, $url);
        return array('file_name' => $filename, 'save_path' => $filename, 'error' => 0);
    }

    public function html2pdf()
    {
        $url = "/mnt/www/test/test.xml";
        $html = file_get_contents($url);
        $PATH = "/mnt/www/test/Uploads/pdfs/";
        $PDF = html2pdf($html, $PATH, $w=414 ,$h=736);
        echo $PDF;
    }

    public function redisPush(){
        // 存入redis队列
        $redis = new RedisAPI();
        $sn = 12345678910;
        for($i=1;$i<=10;$i++){
            $sn += $i;
            echo $sn;
            $redis->rPush("share", $sn . ',' .date("Y-m-d H:i:s"));
        }
    }


    public function redisLpop(){
        // 存入redis队列
        $redis = new RedisAPI();
        $shareInfo = $redis->BLPop("share");
        echo $shareInfo;
    }



    public function dataMove(){
        Session::switchCustomer(0);
        $module_product_order = M("module_product_order");
        $redis = new RedisAPI();

        $ids = $module_product_order->where(['status' => 'ok'])->getField('id',true);
        foreach($ids as $oid){
            $redis->rPush('orderSuccess_log',$oid);
        }
    }

    public function miyouquan(){
        Session::switchCustomer(0);
        $miyouquan = M("miyouquan");
        $sql = "select SUM(`viewUv`) as shareUv,`quanId`   from `wx_mishare_from` GROUP BY `quanId`";
        $arr = M()->query($sql);
        foreach ($arr as $key=>$value){
            if($value['shareUv'] > 0 && $value['quanId']){
                $miyouquan->where(['id' => $value['quanId']])->setField('shareUv',$value['shareUv']);
                echo $miyouquan->getLastSql();
            }
        }
    }

}
